<!DOCTYPE html>
<html>

<head>
  <meta charset='utf-8'>
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name='viewport' content='width=device-width,initial-scale=1.0'>
  <title>jq</title>
  <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.5.0.slim.min.js"></script>
</head>

<body>
  <div><a id="j-rectangler" href="javascript:;">新增</a></div>
  <div id="j-rectangler-imgbox"></div>
  <script>
    function rectangler(options) {
      options = $.extend({}, {
        imgUrl: '',
        width: 1200,
        done: function() {}
      }, options);
      this.data = {};
      this.status = 0;
      this.ratio = 1;
      var thix = this;

      this.draw = function() {
        $('#j-zone').css({
          top: this.data.top + 'px',
          left: this.data.left + 'px',
          width: this.data.wide + 'px',
          height: this.data.height + 'px',
        }).show();
      }

      this.return = function() {
        return {
          top: this.data.top * this.ratio,
          left: this.data.left * this.ratio,
          wide: this.data.wide * this.ratio,
          height: this.data.height * this.ratio
        };
      }

      var img = new Image();
      img.onload = function() {
        thix.ratio = img.width / options.width;
        $('#j-rectangler-imgbox').css({
          position: 'relative',
          width: options.width + 'px'
        }).html($('<img>').attr('src', options.imgUrl).css('width', options.width + 'px')).append('<div id="j-zone" style="position: absolute; border: 1px solid #f00; display: none;"></div>');
        $('#j-rectangler').on('click', function() {
          thix.status = 1;
        });
        $('#j-rectangler-imgbox').on('click', function(e) {
          if (thix.status === 1) {
            thix.status = 2;
            thix.data.left = e.offsetX;
            thix.data.top = e.offsetY;
            thix.data.clientX = e.clientX;
            thix.data.clientY = e.clientY;
          } else if (thix.status === 2) {
            thix.status = 3;
            thix.data.wide = e.clientX - thix.data.clientX;
            thix.data.height = e.clientY - thix.data.clientY;
            thix.draw();
            options.done(thix.return());
          }
        });
        $('#j-rectangler-imgbox').on('mousemove', function(e) {
          if (thix.status === 2) {
            thix.data.wide = e.clientX - thix.data.clientX;
            thix.data.height = e.clientY - thix.data.clientY;
            thix.draw();
          }
        });
      };
      img.src = options.imgUrl;
    }

    new rectangler({
      imgUrl: 'https://docs.microsoft.com/en-us/aspnet/ajax/cdn/overview/_static/image1.png',
      width: 800,
      done: function(r) {
        console.log(r);
        alert('top: ' + r.top + ', left: ' + r.left + ', wide: ' + r.wide + ', height: ' + r.height);
      }
    });

  </script>
</body>

</html>